import { aiService } from '@/utils/ai-service'
import type { ChatMessage } from '@/types/ai-models'

/**
 * AI服务使用示例
 * 演示如何使用不同的国产大模型进行对话
 */

// 示例1: 基本对话
export async function basicChatExample() {
  try {
    // 使用当前默认模型进行对话
    const response = await aiService.quickChat(
      '请介绍一下Vue 3的主要特性',
      '你是一个专业的前端开发助手'
    )
    console.log('AI回答:', response)
  } catch (error) {
    console.error('对话失败:', error)
  }
}

// 示例2: 切换不同模型进行对话
export async function switchProvidersExample() {
  const question = '如何优化JavaScript性能？'
  const systemPrompt = '你是一个资深的JavaScript开发专家'

  try {
    // 使用通义千问
    console.log('=== 通义千问回答 ===')
    const qwenResponse = await aiService.quickChat(question, systemPrompt, {
      provider: 'qwen',
      model: 'qwen-plus-latest'
    })
    console.log(qwenResponse)

    // 使用豆包
    console.log('=== 豆包回答 ===')
    const doubaoResponse = await aiService.quickChat(question, systemPrompt, {
      provider: 'doubao',
      model: 'doubao-seed-1-6-250615'
    })
    console.log(doubaoResponse)

    // 使用DeepSeek推理模型
    console.log('=== DeepSeek推理模型回答 ===')
    const deepseekResponse = await aiService.quickChat(question, systemPrompt, {
      provider: 'deepseek',
      model: 'deepseek-reasoner'
    })
    console.log(deepseekResponse)

  } catch (error) {
    console.error('切换模型对话失败:', error)
  }
}

// 示例3: 多轮对话
export async function multiTurnChatExample() {
  const messages: ChatMessage[] = [
    {
      role: 'system',
      content: '你是一个代码审查助手，帮助开发者改进代码质量'
    },
    {
      role: 'user',
      content: '请帮我审查这段JavaScript代码：\n```js\nfunction getUserData(id) {\n  return fetch("/api/user/" + id).then(res => res.json())\n}\n```'
    }
  ]

  try {
    // 第一轮对话
    const response1 = await aiService.chat(messages, {
      provider: 'deepseek',
      model: 'deepseek-reasoner' // 使用推理模型
    })

    console.log('AI审查意见:', response1.choices[0].message.content)

    // 添加AI回复到对话历史
    messages.push({
      role: 'assistant',
      content: response1.choices[0].message.content
    })

    // 继续对话
    messages.push({
      role: 'user',
      content: '请提供具体的改进代码示例'
    })

    const response2 = await aiService.chat(messages, {
      provider: 'deepseek',
      model: 'deepseek-reasoner'
    })

    console.log('改进建议:', response2.choices[0].message.content)

  } catch (error) {
    console.error('多轮对话失败:', error)
  }
}

// 示例4: 成本计算
export async function costCalculationExample() {
  const messages: ChatMessage[] = [
    { role: 'user', content: '请写一个React函数组件的示例' }
  ]

  try {
    const response = await aiService.chat(messages, {
      provider: 'deepseek',
      model: 'deepseek-reasoner'
    })

    // 计算成本
    const provider = aiService.getCurrentProvider()!
    const cost = aiService.calculateTokenCost(
      provider,
      'deepseek-reasoner',
      response.usage.prompt_tokens,
      response.usage.completion_tokens
    )

    console.log(`Token使用情况:`)
    console.log(`- 输入tokens: ${response.usage.prompt_tokens}`)
    console.log(`- 输出tokens: ${response.usage.completion_tokens}`)
    console.log(`- 总tokens: ${response.usage.total_tokens}`)
    console.log(`- 预估成本: $${cost.toFixed(6)}`)

  } catch (error) {
    console.error('成本计算示例失败:', error)
  }
}

// 示例5: 配置管理
export function configurationExample() {
  // 查看所有可用的提供商
  console.log('可用的AI提供商:')
  aiService.getAvailableProviders().forEach(provider => {
    console.log(`- ${provider.name} (${provider.id})`)
    provider.models.forEach(model => {
      console.log(`  * ${model.name}: ${model.description}`)
    })
  })

  // 设置API密钥
  aiService.setApiKey('qwen', 'your-qwen-api-key')
  aiService.setApiKey('doubao', 'your-doubao-api-key')
  aiService.setApiKey('deepseek', 'your-deepseek-api-key')

  // 更新设置
  aiService.updateSettings({
    temperature: 0.8,
    maxTokens: 4000
  })

  // 切换默认提供商
  aiService.setCurrentProvider('qwen')

  // 查看状态
  const status = aiService.getProviderStatus()
  console.log('提供商状态:', status)
}

// 示例6: 错误处理和重试机制
export async function errorHandlingExample() {
  const maxRetries = 3
  let attempt = 0

  while (attempt < maxRetries) {
    try {
      const response = await aiService.quickChat('你好，介绍一下你自己')
      console.log('AI回答:', response)
      break // 成功则跳出循环
    } catch (error) {
      attempt++
      console.log(`第${attempt}次尝试失败:`, error)

      if (attempt >= maxRetries) {
        console.error('所有重试都失败了')
        
        // 尝试切换到其他提供商
        const providers = ['qwen', 'doubao', 'deepseek']
        for (const providerId of providers) {
          try {
            console.log(`尝试切换到 ${providerId}...`)
            const response = await aiService.quickChat('你好', undefined, {
              provider: providerId
            })
            console.log(`${providerId} 响应成功:`, response)
            break
          } catch (switchError) {
            console.log(`${providerId} 也失败了:`, switchError)
          }
        }
      } else {
        // 等待一段时间后重试
        await new Promise(resolve => setTimeout(resolve, 1000 * attempt))
      }
    }
  }
}

// 导出所有示例函数供测试使用
export const examples = {
  basicChatExample,
  switchProvidersExample,
  multiTurnChatExample,
  costCalculationExample,
  configurationExample,
  errorHandlingExample
}